# coding:utf-8
from urllib import request
from urllib import parse
import requests
import ssl
import re
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
ssl._create_default_https_context = ssl._create_unverified_context

url = "https://sso.hikvision.com/login?http://psh.hikvision.com.cn:8080/sso/page/command?pageName=home"

headers = {
    #heard部分直接通过chrome部分request header部分
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Accept-Encoding':'gzip, deflate, br',
    'Accept-Language':'zh-CN,zh;q=0.9',
    'Connection':'keep-alive',
    'Content-Length':'1459', #get方式提交的数据长度，如果是post方式，转成get方式：【id=wdb&pwd=wdb】
    'Content-Type':'text/html;charset=UTF-8',
    'Host': 'sso.hikvision.com',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
    'Upgrade-Insecure-Requests': '1',
    'Cookie': 'UM_distinctid=16c7b2856a3a9-08716f872bd1a1-7373e61-100200-16c7b2856a521; LastVisitUserName=lichuanjiang; JSESSIONID=8F533827D4720A4FF89DE631E625B037',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
 
}
 
#data = parse.urlencode(data).encode('utf-8')
#req = request.Request(url, headers=headers, data=data)  #POST方法
req = request.Request(url)  # GET方法
print(req.headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')
#print(page)
ret1 = re.findall(r"lt.+", page)
ret2 = re.findall(r"execution.+", page)
ret3 = re.findall(r"_eventId.+", page)
ret = []
ret.append(ret1)
ret.append(ret2)
ret.append(ret3)
a=[]
for x in ret:
    x = re.findall("(?<=value=\").*(?=\")",str(x))
    a.append(x)
print(a)
#print(ret)

#请求页面的lt  execution  eventid的值

session = requests.session()
content = {'username': 'yonghuming', 'password': 'mima++', 'lt': a[0], 'execution': a[1], '_eventId': a[2]}
headerslogin = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
    'Cookie': 'UM_distinctid=16c7b2856a3a9-08716f872bd1a1-7373e61-100200-16c7b2856a521; LastVisitUserName=lichuanjiang; JSESSIONID=8F533827D4720A4FF89DE631E625B037; expires=Sat, 31 Aug 2019 07:45:46 GMT'
}
res = session.post(url, headers=headerslogin, data=content, verify=False)
# Location = res.headers
print(res.headers)
# print(res.text)
